<?php
namespace Common\Behavior;
use Think\Behavior;
/*
 * API初始化
 */
class ApiInitBehavior extends Behavior
{
	public function run(&$params)
	{
		if(BIND_MODULE === 'Home') {
			//if(I('json','', '/^\{.+\}$/')) {
				//获取JSON格式参数

				if($_GET['s']){
					return;
				}

				$json = I('json');
				if(!$json) die($this->jsonStr(array('error' => 1, 'info' => '接口参数错误')));
				$json = json_decode($json, true);
				if(!$json) die($this->jsonStr(array('error' => 1, 'info' => '参数格式错误')));

				//获取API CODE
				$apiCode = $json['apiCode'];
				
				if($apiCode) {
					$api = api_info($apiCode);
					if(!$api || !$api['module'] || !$api['controller'] || !$api['action']) die($this->jsonStr(array('error' => 1, 'info' => 'API服务未声明')));
					
					//判断接口请求方式
					$api['method'] = intval($api['method']);
					if($api['method'] === 2) {
						!IS_GET && die($this->jsonStr(array('error' => 1, 'info' => '接口请求只支持GET方式')));
					} else if($api['method'] === 3) {
						!IS_POST && die($this->jsonStr(array('error' => 1, 'info' => '接口请求只支持POST方式')));
					} else if($api['method'] === 1) {
						!IS_GET && !IS_POST && die($this->jsonStr(array('error' => 1, 'info' => '接口请求方式错误')));
					}
					
					//获取相关参数，验证必要参数
					$token = $json['token'];
					if(!$token) die($this->jsonStr(array('error' => 1, 'info' => '缺少token')));
					unset($json['token']);
					unset($json['apiCode']);
					$param = $json;
					if(gettype($param) !== 'array' && !$param) die($this->jsonStr(array('error' => 1, 'info' => '业务参数错误')));
	
					//签名
					$json['apiCode'] = $apiCode;
					$tmp = api_sign($json);

//					$file = fopen("/data/www/qgh.log","w");
//					fwrite($file,$tmp.json_encode($json));
//					fclose($file);
					//验证请求数据安全性
					if($token !== $tmp) die($this->jsonStr(array('error' => 1, 'info' => '请传递正确的token')));
					
					//重置模块、控制器和操作
					$_GET[C('VAR_CONTROLLER')] = $api['controller'];
					$_GET[C('VAR_ACTION')] = $api['action'];
					$_GET[C('VAR_MODULE')] = $api['module'];
					
					//POST请求
					if(IS_POST) {
						$m = &$_POST;
					}
					
					//GET请求
					if(IS_GET) {
						$m = &$_GET;
					}
					unset($m['param']);
					$m['params'] = $param;

					define('API_CODE', $apiCode);
					unset($m['json']);
				} else {
					die($this->jsonStr(array('error' => 1, 'info' => '请传入API code')));
				}
		}
	}
	
	/**
	 * 返回JSON字符串
	 * @param array $param
	 * @return string
	 * @author 刘新
	 */
	public function jsonStr(array $param) 
	{
		return json_encode($param, JSON_UNESCAPED_UNICODE);
	}
}
